import React from 'react';
// import { connect } from 'react-redux';
import { TreeSelect } from 'antd';
// import { getCategories } from  "../../../actions/categoryActions";
import { listToTree } from '../../common' ; 

var _ = require('lodash');
const TreeNode = TreeSelect.TreeNode;

class CategoryTreeSeletor extends React.Component{
    onChange = (checkedKeys, info) => {
        if (typeof(this.props.onSelected) === "function") {
            this.props.onSelected(checkedKeys);
        }
        this.props.onChange(checkedKeys);
    }

    render(){
        const loop = data => Object.keys(data).map ( (item) => {
            let node = data[item];
            const title = node.title;
            if ( _.isEmpty(node.children) ) {
                return <TreeNode title={title} key={item} value={item} isLeaf={true}/>;
            }else {
                return <TreeNode title={title} key={item} value={item} >{loop(node.children)}</TreeNode>;
            }
        });
        const initialValue = this.props.value+'';
        const treeData = listToTree(this.props.treeData ,{
                            idKey: 'id',
                            parentKey: 'parent_id',
                            childrenKey: 'children'
                        });
        return (
                <TreeSelect
                            style={{ width: 300 }}
                            treeDefaultExpandAll
                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                            onChange={this.onChange}
                            value={initialValue}
                        >
                         {loop(treeData)}
                </TreeSelect>
        )
    }
}


CategoryTreeSeletor.propTypes = {
    treeData:React.PropTypes.array.isRequired,
};

export default CategoryTreeSeletor;